<?php
/**
 * Created by PhpStorm.
 * User: Lyq
 * Date: 2018/8/19
 * Time: 上午9:23
 */
namespace app\admin\controller;

use think\Exception;
use think\Db;

class Union extends Common
{
    //分类列表
    public function category()
    {
        //标题
        $this->templateTitle('联盟商分类管理');

        //判断条件
        $where=[];

        //搜索条件
        $condition = request()->param("condition");
        $this->assign("condition", $condition);
        if ($condition)
        {
            $where["title"] = ["LIKE", "%$condition%"];
        }

        //获取新闻分类
        $list = Db::name("union_category")
            ->where($where)
            ->order("display_order DESC,update_time DESC")
            ->paginate(10);
        $this->assign("list", $list);

        return $this->fetch();
    }

    //添加分类
    public function addCategory()
    {
        if (request()->isGet())
        {
            $this->layoutModal();

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传缩略图');
            }
            //分类描述
            $data["description"] = request()->param("desc");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try
            {
                $add = Db::name("union_category")->insert($data);
                if($add){
                    $this->ajaxSuccess('联盟分类添加成功');
                }else{
                    $this->ajaxError('联盟商分类添加失败');
                }

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //编辑新闻分类
    public function editCategory()
    {
        //分类ID
        $categoryId = request()->param("cid");

        if (request()->isGet())
        {
            $this->layoutModal();

            //获取分类信息
            $category = Db::name("union_category")
                ->where("id", $categoryId)
                ->find();
            $this->assign("category", $category);
            //处理缩略图
            $this->assign("single_image", array("thumb"=>$category["thumb"]));
            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            //分类名称
            $data["title"] = request()->param("title");
            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传缩略图');
            }
            //分类描述
            $data["description"] = request()->param("desc");
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try
            {
                //更新分类ID路径
                $save = Db::name("union_category")
                    ->where("id", $categoryId)
                    ->update($data);
                if($save){
                    $this->ajaxSuccess('编辑联盟商分类成功');
                }else{
                    $this->ajaxError('编辑联盟商分类失败');
                }

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除新闻分类
    public function removeCategory()
    {
        if (request()->isAjax())
        {
            //分类ID
            $categoryId = request()->param("cid");

            try
            {
                //更新分类ID路径
                $del = Db::name("union_category")
                    ->where("id", $categoryId)
                    ->delete();
                if($del){
                    $this->ajaxSuccess('联盟商分类删除成功');
                }else{
                    $this->ajaxError('联盟商分类删除失败');
                }

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function index(){
        //标题
        $this->templateTitle("联盟商列表");
        $this->assign('category_list',$this->get_union_category_list());
        $where['un.id'] = ['gt',0] ;

        //省
        $pro = trim(input('pro'));
        $this->assign('area_province',$pro);
        if($pro){
            $where['un.pro'] = $pro;
        }
        //市
        $city = trim(input('city'));
        $this->assign('area_city',$city);
        if($city){
            $where['un.city'] = $city;
        }
        //分类
        $cid = request()->param('cid');
        $this->assign('cid',$cid);
        if($cid){
            $where['uc.id'] = $cid;
        }
        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        $this->assign("user_condition", $user_condition);
        if ($user_condition)
        {
            $where["us.real_name|us.mobile|us.id"] = $user_condition;
        }

        //搜索条件-联盟商名称
        $condition = request()->param("condition");
        $this->assign("condition", $condition);
        if ($condition)
        {
            $where["un.title"] = ["LIKE", "%$condition%"];
        }

        //获取所有用户
        $list = Db::name("union")
            ->alias("un")
            ->join("__USER__ us", "un.uid=us.id",'LEFT')
            ->join("__UNION_CATEGORY__ uc", "un.category_id=uc.id",'LEFT')
            ->where($where)
            ->order("un.display_order DESC,un.update_time DESC")
            ->field('un.*,us.mobile as umobile,us.real_name as uname,us.money as umoney,uc.title as categoty_name')
            ->paginate(10);

        $this->assign("list", $list);

        return $this->fetch();
    }
    public function add()
    {
        if (request()->isGet())
        {
            $this->layoutModal();
            $this->assign('category_list',$this->get_union_category_list());

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );

            //所属会员
            $data["uid"] = request()->param("uid");
            if(empty($data['uid'])){
                return $this->ajaxError('请输入会员ID');
            }

            $user = Db::name('user')->where('id',$data['uid'])->find();
            if(!$user || $user['in_blacklist']==1){
                return $this->ajaxError('绑定的会员【ID：'.$data['uid'].'】不存在或已拉黑');
            }

            $count = Db::name('union')->where('uid',$data['uid'])->count();
            if($count){
                return $this->ajaxError('此会员【ID：'.$data['uid'].'】已被绑定，每个会员只允许绑定一次');
            }

            //联盟商分类
            $data["category_id"] = request()->param("type");
            if(empty($data['category_id'])){
                return $this->ajaxError('请选择联盟商分类');
            }

            //活动主题
            $data["title"] = request()->param("title");
            if(empty($data['title'])){
                return $this->ajaxError('请输入联盟商名称');
            }

            $data['cut_percent'] = request()->param('cut_percent');

            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传LOGO');
            }

            //背景图片
            $data["background"] = request()->param("background");
            if(empty($data['background'])){
                return $this->ajaxError('请上传背景图片');
            }

            $data['pro'] = request()->param("pro");
            if(empty($data['pro'])){
                return $this->ajaxError('请选择省份');
            }
            $data['city'] = request()->param("city");
            if(empty($data['city'])){
                return $this->ajaxError('请选择城市');
            }

            $data['tel'] = request()->param('tel');

            //详细地址
            $data["address"] = request()->param("address");
            if(empty($data['address'])){
                return $this->ajaxError('请输入详细地址');
            }
            $data['longitude'] = request()->param('longitude');
            $data['latitude'] = request()->param('latitude');
            if(empty($data['longitude'])||empty($data['latitude'])){
                return $this->ajaxError('请输入详细地址定位获取坐标');
            }
            //排序
            $data["display_order"] = request()->param("order");
            $data["is_visible"] = request()->param("visible");
            $data["is_recommend"] = request()->param("recommend");
//            $data["in_blacklist"] = request()->param("in_blacklist");
            //详情
            $detail = request()->param("article_detail");
            $data["detail"] = $detail;

            try
            {
                $save = Db::name("union")->insert($data);
                if($save){

                    Db::name('user')
                        ->where('id',$data['uid'])
                        ->update(['is_union'=>1]);

                    $this->ajaxSuccess('联盟商添加成功');
                }else{
                    $this->ajaxError('服务器繁忙，请稍后再试');
                }
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function edit()
    {   $id = request()->param('id');
        if (request()->isGet())
        {
            $this->layoutModal();
            $this->assign('category_list',$this->get_union_category_list());
            $info = Db::name('union')->where('id',$id)->find();
            $this->assign('info',$info);
            $this->assign('map_address',$info['address']);
            $this->assign('map_longitude',$info['longitude']);
            $this->assign('map_latitude',$info['latitude']);
            //处理图片
            $this->assign("single_image", array("thumb"=>$info["thumb"],"background"=>$info['background']));
            //处理详细内容
            $this->assign("ueditor_content", array("article_detail"=>$info["detail"]));
            $this->assign("area_province", $info['pro']);
            $this->assign("area_city", $info['city']);
            $this->assign("user_id", $info['uid']);
            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );

            //所属会员-先禁止编辑绑定的会员id 避免数据混乱
//            $data["uid"] = request()->param("uid");
//            if(empty($data['uid'])){
//                return $this->ajaxError('请输入会员ID');
//            }
//
//            $user = Db::name('user')->where('id',$data['uid'])->find();
//            if(!$user || $user['in_blacklist']==1){
//                return $this->ajaxError('绑定的会员【ID：'.$data['uid'].'】不存在或已拉黑');
//            }
//
//            $count = Db::name('union')
//                ->where('uid',$data['uid'])
//                ->where('id','neq',$id)
//                ->count();
//            if($count){
//                return $this->ajaxError('此会员【ID：'.$id.'】已被绑定，每个会员只允许绑定一次');
//            }

            //联盟商分类
            $data["category_id"] = request()->param("type");
            if(empty($data['category_id'])){
                return $this->ajaxError('请选择联盟商分类');
            }

            //活动主题
            $data["title"] = request()->param("title");
            if(empty($data['title'])){
                return $this->ajaxError('请输入联盟商名称');
            }

            $data['cut_percent'] = request()->param('cut_percent');

            //缩略图
            $data["thumb"] = request()->param("thumb");
            if(empty($data['thumb'])){
                return $this->ajaxError('请上传LOGO');
            }

            //背景图片
            $data["background"] = request()->param("background");
            if(empty($data['background'])){
                return $this->ajaxError('请上传背景图片');
            }

            $data['pro'] = request()->param("pro");
            if(empty($data['pro'])){
                return $this->ajaxError('请选择省份');
            }
            $data['city'] = request()->param("city");
            if(empty($data['city'])){
                return $this->ajaxError('请选择城市');
            }

            $data['tel'] = request()->param('tel');

            //详细地址
            $data["address"] = request()->param("address");
            if(empty($data['address'])){
                return $this->ajaxError('请输入详细地址');
            }
            $data['longitude'] = request()->param('longitude');
            $data['latitude'] = request()->param('latitude');
            if(empty($data['longitude'])||empty($data['latitude'])){
                return $this->ajaxError('请输入详细地址定位获取坐标');
            }
            //排序
            $data["display_order"] = request()->param("order");
            $data["is_visible"] = request()->param("visible");
            $data["is_recommend"] = request()->param("recommend");
//            $data["in_blacklist"] = request()->param("in_blacklist");
            //详情
            $detail = request()->param("article_detail");
            $data["detail"] = $detail;

            try
            {
                $save = Db::name("union")
                    ->where('id',$id)
                    ->update($data);
                if($save){
                    Db::name('union_discount')
                        ->where('union_id',$id)
                        ->update(['category_id'=>$data['category_id']]);
                    $this->ajaxSuccess('编辑联盟商成功');
                }else{
                    $this->ajaxError('服务器繁忙，请稍后再试');
                }
            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function recommend()
    {
        if (request()->isAjax())
        {
            $articleId = request()->param("aid");
            //推荐状态
            $status = request()->param("status");

            Db::name("union")
                ->where("id", $articleId)
                ->update(array(
                    "is_recommend" => $status,
                    "update_time" => now_datetime(),
                ));

            $this->ajaxSuccess('推荐状态修改成功');
        }
    }

    public function blacklist()
    {
        if (request()->isAjax())
        {
            $id = request()->param("id");
            //推荐状态
            $status = request()->param("status");

            if(!in_array($status,[0,1])){
                return $this->ajaxError('操作参数有误');
            }

            $s = Db::name("union")
                ->where("id", $id)
                ->update(array(
                    "in_blacklist" => $status,
                    "update_time" => now_datetime(),
                ));
            if($s){
                if($status==1){
                    //加入黑名单
                    //删除卡券
                    Db::name("union_discount")
                        ->where("union_id", $id)
                        ->delete();
                    return $this->ajaxSuccess('拉黑操作成功');
                }else{
                    return $this->ajaxSuccess('取消拉黑操作成功');
                }

            }else{
                return $this->ajaxError('服务器繁忙，请稍后再试');
            }
        }
    }

    protected function get_union_category_list(){
        $list = Db::name('union_category')
            ->where('is_visible',1)
            ->order('display_order DESC,update_time DESC')
            ->field('id,title')
            ->select();
        if($list){
            return $list;
        }else{
            return [];
        }
    }

    public function discount(){
        //标题
        $this->templateTitle("卡券列表");
        $where['ui.id'] = ['gt',0] ;


        //搜索条件-联盟商
        $un_condition = request()->param("un_condition");
        $this->assign("un_condition", $un_condition);
        if ($un_condition)
        {
            $where["un.title|un.id"] = $un_condition;
        }

        //搜索条件-标题
        $condition = request()->param("condition");
        $this->assign("condition", $condition);
        if ($condition)
        {
            $where["ui.title"] = ['like','%'.$condition.'%'];
        }

        //获取所有
        $list = Db::name("union_discount")
            ->alias("ui")
            ->join("__UNION__ un", "ui.union_id=un.id",'LEFT')
            ->where($where)
            ->order("ui.display_order DESC,ui.update_time DESC")
            ->field('ui.*,un.title as union_name')
            ->paginate(10);

        $this->assign("list", $list);

        return $this->fetch();
    }

    public function delDiscount(){
        if(request()->isAjax()){
            $id = request()->param('id');
            $del = Db::name('union_discount')
                ->where('id',$id)
                ->delete();
            if($del){
                return $this->ajaxSuccess('卡券删除成功');
            }else{
                return $this->ajaxSuccess('卡券删除失败');
            }
        }
    }

    public function addDiscount()
    {
        if (request()->isGet())
        {
            $this->layoutModal();

            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );

            $union_id = request()->param('union_id');
            $union_id = intval($union_id);
            if(empty($union_id)){
                return $this->ajaxError('请选择所属联盟商');
            }

            $count = Db::name('union_discount')
                ->where('union_id',$union_id)
                ->count();
            if($count){
                return $this->ajaxError('联盟商【ID：'.$union_id.'】已绑定卡券，一个联盟商只能绑定一次');
            }
            $data['union_id'] = $union_id;

            $union = Db::name('union')->where('id',$union_id)->find();
            if(!$union||$union['in_blacklist']){
                return $this->ajaxError('联盟商不存在或已拉黑');
            }
            $data['category_id'] = $union['category_id'];
            //分类名称
            $data["title"] = request()->param("title");
            $data['thumb'] = request()->param('thumb');
            if(empty($data['thumb'])){
                return $this->ajaxError('请选择背景色');
            }
            $data['discount'] = intval(request()->param('discount'));
            if(empty($data['discount'])){
                return $this->ajaxError('请输入卡券折扣');
            }
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try
            {
                $add = Db::name("union_discount")->insert($data);
                if($add){
                    $this->ajaxSuccess('卡券添加成功');
                }else{
                    $this->ajaxError('卡券添加失败');
                }

            }
            catch (Exception $exception)
            {
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function editDiscount()
    {
        //分类ID
        $id = request()->param("id");

        if (request()->isGet()) {
            $this->layoutModal();

            $info = Db::name('union_discount')->where('id', $id)->find();
            $this->assign('info', $info);

            //处理缩略图
            $this->assign("default_color",$info["thumb"]);
            $this->assign('union_id', $info['union_id']);
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );

            $union_id = request()->param('union_id');
            $union_id = intval($union_id);
            if (empty($union_id)) {
                return $this->ajaxError('请选择所属联盟商');
            }

            $count = Db::name('union_discount')
                ->where('id', 'neq', $id)
                ->where('union_id', $union_id)
                ->count();
            if ($count) {
                return $this->ajaxError('联盟商【ID：' . $union_id . '】已绑定卡券，一个联盟商只能绑定一次');
            }
            $data['union_id'] = $union_id;

            $union = Db::name('union')->where('id', $union_id)->find();
            if (!$union || $union['in_blacklist']) {
                return $this->ajaxError('联盟商不存在或已拉黑');
            }
            $data['category_id'] = $union['category_id'];
            //分类名称
            $data["title"] = request()->param("title");
            $data['thumb'] = request()->param('thumb');
            if (empty($data['thumb'])) {
                return $this->ajaxError('请选择背景色');
            }
            $data['discount'] = intval(request()->param('discount'));
            if (empty($data['discount'])) {
                return $this->ajaxError('请输入卡券折扣');
            }
            //分类排序
            $data["display_order"] = request()->param("order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            try {
                $save = Db::name("union_discount")->where('id', $id)->update($data);
                if ($save) {
                    $this->ajaxSuccess('卡券编辑成功');
                } else {
                    $this->ajaxError('卡券编辑失败');
                }

            } catch (Exception $exception) {
                $this->ajaxError($exception->getMessage());
            }
        }
    }
}